import React, { useRef, useState } from 'react';
import { PageContainer, ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, message, Modal, Form, Input, Select, Space, Tag } from 'antd';
import { api } from '@/services/api';
import { Link, LinkRequest, Category, Tag as TagType } from '@/services/generated/models';

const LinkList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editingLink, setEditingLink] = useState<Link | null>(null);
  const [categories, setCategories] = useState<Category[]>([]);
  const [tags, setTags] = useState<TagType[]>([]);

  // 获取分类和标签数据
  const fetchOptions = async () => {
    try {
      const [categoriesResponse, tagsResponse] = await Promise.all([
        api.navigation.navigationCategoriesList({}),
        api.navigation.navigationTagsList({}),
      ]);
      setCategories(categoriesResponse || []);
      setTags(tagsResponse || []);
    } catch (error) {
      message.error('获取选项数据失败');
    }
  };

  React.useEffect(() => {
    fetchOptions();
  }, []);

  const handleSubmit = async (values: LinkRequest) => {
    try {
      // 创建或更新链接
      if (editingLink) {
        await api.navigation.navigationLinksUpdate({
          id: editingLink.id,
          linkRequest: values,
        });
        message.success('更新成功');
      } else {
        await api.navigation.navigationLinksCreate({
          linkRequest: values,
        });
        message.success('创建成功');
      }

      // 如果有标签，更新标签
      if (values?.tags?.length) {
        try {
          await api.navigation.navigationLinksUpdateTagsCreate({
            id: editingLink.id,
            linkTagsUpdateRequest: {
              tagIds: values.tags,
            },
          });
        } catch (error) {
          console.error('更新标签失败:', error);
          message.error('更新标签失败');
        }
      }

      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      console.error('操作失败:', error);
      message.error('操作失败');
    }
  };

  const columns: ProColumns<Link>[] = [
    {
      title: '标题',
      dataIndex: 'title',
      copyable: true,
      ellipsis: true,
      fixed: 'left',
    },
    {
      title: 'URL',
      dataIndex: 'url',
      copyable: true,
      ellipsis: true,
      fixed: 'left',
    },
    {
      title: '分类',
      dataIndex: 'category',
      valueType: 'select',
      valueEnum: Object.fromEntries(
        categories.map((cat) => [cat.id, { text: cat.name }])
      ),
      render: (_, record) => record?.categoryName,
    },
    {
      title: '标签',
      dataIndex: 'tags',
      render: (_, record) => (
        <Space wrap>
          {record.tags?.map((tag) => (
            <Tag key={tag.id} color="blue">
              {tag.name}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="visit"
          type="link"
          onClick={() => window.open(record.url, '_blank')}
        >
          访问
        </Button>,
        <Button
          key="edit"
          type="link"
          onClick={() => {
            setEditingLink(record);
            form.setFieldsValue({
              ...record,
              category: record.category,
              tags: record.tags?.map(t => t.id),
            });
            setModalVisible(true);
          }}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="link"
          danger
          onClick={async () => {
            try {
              await api.navigation.navigationLinksDestroy({
                id: record.id,
              });
              message.success('删除成功');
              actionRef.current?.reload();
            } catch (error) {
              message.error('删除失败');
            }
          }}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<Link>
        headerTitle="链接列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: 'max-content' }}
        search={{
          filterType: 'light',
          defaultCollapsed: true,
          span: 6,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            onClick={() => {
              setEditingLink(null);
              form.resetFields();
              setModalVisible(true);
            }}
          >
            新建链接
          </Button>,
        ]}
        request={async (params) => {
          try {
            const response = await api.navigation.navigationLinksList({
              title: params.title,
              category: params.category,
            });
            return {
              data: response || [],
              success: true,
              total: response?.length || 0,
            };
          } catch (error) {
            message.error('获取数据失败');
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />

      <Modal
        title={editingLink ? '编辑链接' : '新建链接'}
        visible={modalVisible}
        onOk={() => form.submit()}
        onCancel={() => setModalVisible(false)}
        width={720}
        destroyOnClose
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="url"
            label="URL"
            rules={[
              { required: true, message: '请输入URL' },
              { type: 'url', message: '请输入有效的URL' },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select>
              {categories.map((cat) => (
                <Select.Option key={cat.id} value={cat.id}>
                  {cat.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="tags"
            label="标签"
          >
            <Select mode="multiple">
              {tags.map((tag) => (
                <Select.Option key={tag.id} value={tag.id}>
                  {tag.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item
            name="icon"
            label="图标"
          >
            <Input placeholder="输入图标URL或选择图标" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default LinkList;
